package com.szt.sy.service.system.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.szt.sy.common.AuthorityCommon;
import com.szt.sy.entity.SessionUser;
import com.szt.sy.entity.system.Button;
import com.szt.sy.entity.system.Menu;
import com.szt.sy.entity.system.Role;
import com.szt.sy.entity.system.RoleButton;
import com.szt.sy.entity.system.RoleMenu;
import com.szt.sy.entity.system.User;
import com.szt.sy.mapper.system.UserMapper;
import com.szt.sy.service.system.button.ButtonService;
import com.szt.sy.service.system.menu.MenuService;
import com.szt.sy.service.system.role.RoleService;
import com.szt.sy.service.system.rolebutton.RoleButtonService;
import com.szt.sy.service.system.rolemenu.RoleMenuService;

/***
 * 系统用户服务
 * 
 * @author wwy
 *
 */
@Service("userService")
@Transactional(rollbackFor = RuntimeException.class)
public class UserService extends ServiceImpl<UserMapper, User> implements UserDetailsService {
	
	@Autowired
	private MenuService menuService;
	
	@Autowired
	private ButtonService buttonService;
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private RoleMenuService roleMenuService;
	
	@Autowired
	private RoleButtonService roleButtonService;
	
	/**
	 * 登录判断
	 *
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public User getUserByNameAndPwd(String name, String password, String id) {
		User user = new User();
		if (StringUtils.isNotBlank(name) && StringUtils.isNotBlank(password)) {
			user.setPassword(password);
			user.setName(name);
		}
		if (StringUtils.isNotBlank(id)) {
			user.setId(id);
		}
		user.setDel(false);
		return baseMapper.selectOne(user);
	}
	
	/***
	 * 通过name获得user
	 *
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public User getUserByName(String name) {
		User user = new User();
		user.setName(name);
		user.setDel(false);
		return baseMapper.selectOne(user);
	}
	
	/***
	 * 更新最近登录信息
	 * 
	 * @param userId
	 * @param ip
	 */
	public void updateLastLogin(String userId, String ip) {
		User user = new User();
		user.setLastLogin(new Date());
		user.setIp(ip);
		baseMapper.update(user, new EntityWrapper<User>().eq("id", userId));
	}
	
	/**
	 * 通过用户ID获取用户信息和角色信息
	 *
	 * @param USER_ID
	 * @return
	 * @throws Exception
	 */
	public User getUserAndRoleById(String id) {
		return baseMapper.getUserAndRoleById(id);
	}
	
	/**
	 * 通过USERNAEME获取数据
	 *
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public User findByUsername(String name) {
		return baseMapper.findByUsername(name);
	}
	
	/**
	 * 列出某角色下的所有用户
	 *
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public List<User> listAllUserByRoldId(String roleId) {
		return baseMapper.selectList(new EntityWrapper<User>().eq("roleId", roleId));
		
	}
	
	/**
	 * 保存用户IP
	 *
	 * @param pd
	 * @throws Exception
	 */
	public void saveIP(String name, String ip) {
		User user = new User();
		user.setIp(ip);
		baseMapper.update(user, new EntityWrapper<User>().eq("name", name));
	}
	
	/**
	 * 用户列表
	 *
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public Page<User> listUsers(Page<User> page, Map<String, Object> map) {
		page.setRecords(baseMapper.userlistPage(page, map));
		return page;
	}
	
	/**
	 * 通过邮箱获取数据
	 *
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public User findByUE(String email, String name) {
		User user = new User();
		user.setEmail(email);
		user.setName(name);
		return baseMapper.selectOne(user);
	}
	
	/**
	 * 通过id获取数据
	 *
	 * @param pd
	 * @return
	 * @throws Exception
	 */
	public User findById(String id) {
		return baseMapper.selectById(id);
	}
	
	/**
	 * 获取数据记录条数
	 *
	 * @param id
	 * @throws Exception
	 */
	public Integer findCount() {
		return baseMapper.selectCount(new EntityWrapper<User>());
	}
	
	/**
	 * 保存用户
	 *
	 * @param pd
	 * @throws Exception
	 */
	public void saveU(User entity) {
		
		baseMapper.insert(entity);
	}
	
	/**
	 * 修改用户
	 *
	 * @param pd
	 * @throws Exception
	 */
	public void editU(User entity) {
		baseMapper.updateById(entity);
	}
	
	/**
	 * 删除用户
	 *
	 * @param pd
	 * @throws Exception
	 */
	public void deleteU(String id) {
		baseMapper.delete(new EntityWrapper<User>().eq("id", id).ne("id", "1"));
	}
	
	/**
	 * 批量删除用户
	 *
	 * @param USER_IDS
	 * @throws Exception
	 */
	public void deleteAllU(String[] ids) {
		baseMapper.deleteAllU(ids);
	}
	
	/**
	 * 用户列表(全部)
	 *
	 * @param USER_IDS
	 * @throws Exception
	 */
	public List<User> listAllUser(Map<String, Object> map) {
		return baseMapper.listAllUser(map);
	}
	
	/**
	 * 获取总数
	 *
	 * @param pd
	 * @throws Exception
	 */
	public Integer getUserCount() {
		return baseMapper.selectCount(new EntityWrapper<User>());
	}
	
	/**
	 * 列表
	 *
	 * @param page
	 * @return
	 * @throws Exception
	 */
	public Page<User> list(Page<User> page, Map<String, Object> map) {
		page.setRecords(baseMapper.datalistPage(page, map));
		return page;
	}
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SessionUser sessionUser = new SessionUser();
		User user = findByUsername(username);
		if (user != null) {
			Role role = roleService.selectById(user.getRoleId());
			user.setRole(role);
		}
		sessionUser.setUser(user);
		return sessionUser;
	}
	
	/***
	 * 根据用户获取权限
	 * 
	 * @param user
	 * @return
	 */
	public List<SimpleGrantedAuthority> getAuthoritiesByUser(User user) {
		if (user.getAllRights()) {
			// 超级管理员，获取全部权限
			return getAllGrantedAuthority();
		}
		// 获取菜单权限
		List<SimpleGrantedAuthority> authorityList = new ArrayList<>(30);
		List<RoleButton> roleButtonList = roleButtonService.selectMoreInfoByRoleId(user.getRoleId());
		List<RoleMenu> roleMenuList = roleMenuService.selectMoreInfoByRoleId(user.getRoleId());
		for (RoleMenu roleMenu : roleMenuList) {
			authorityList.add(new SimpleGrantedAuthority(roleMenu.getMenuUrl()));
		}
		for (RoleButton roleButton : roleButtonList) {
			authorityList.add(new SimpleGrantedAuthority(
					StringUtils.join(new String[] { roleButton.getMenuUrl(), roleButton.getButtonAuthority() },
							AuthorityCommon.DELIMITER)));
		}
		return authorityList;
	}
	
	/****
	 * 获取全部权限
	 * 
	 * @return
	 */
	public List<SimpleGrantedAuthority> getAllGrantedAuthority() {
		List<SimpleGrantedAuthority> authorityList = new ArrayList<>(30);
		List<Menu> menuList = menuService.selectList(new EntityWrapper<Menu>());
		List<Button> buttonList = buttonService.selectList(new EntityWrapper<Button>());
		for (Menu menu : menuList) {
			// 菜单权限,格式:菜单链接
			authorityList.add(new SimpleGrantedAuthority(menu.getMenuUrl()));
			for (Button button : buttonList) {
				// 按钮权限,格式:菜单链接:按钮权限名称
				authorityList.add(new SimpleGrantedAuthority(StringUtils.join(
						new String[] { menu.getMenuUrl(), button.getAuthorityName() }, AuthorityCommon.DELIMITER)));
			}
		}
		return authorityList;
	}
	
}
